package com.ctn.information.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;


public class JsonUtil {
	
	
	/**
	 * 转抱JSON对像为java object.
	 * @param convert
	 * @param json
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws ClassNotFoundException
	 * @throws JSONException
	 */
	public static void convertJsonToObj(Object convert, JSONObject json)
			throws IllegalArgumentException, IllegalAccessException,
			InstantiationException, ClassNotFoundException, JSONException {
		Class objClass = convert.getClass();
		Field[] fields = objClass.getDeclaredFields();
		String jsonFied = null;
		for (Field f : fields) {
			if (f.getName().equals("serialVersionUID")) {
				continue;
			}
			JsonField anno = f.getAnnotation(JsonField.class);
			if (anno != null) {
				jsonFied = anno.value();
			} else {
				jsonFied = f.getName();
			}
			f.setAccessible(true);
			if (f.getType().getName().equals("java.util.List")) {
				Object jsonObject = json.get(jsonFied);
				if (jsonObject == null) {
					continue;
				}
				if (jsonObject instanceof JSONArray) {
					JSONArray jsonArray = (JSONArray) jsonObject;
					List list = new ArrayList();
					f.set(convert, list);
					String genericTyp = f.getGenericType().toString();
					String className = genericTyp.substring(
							genericTyp.indexOf("<") + 1,
							genericTyp.indexOf(">"));
					for (int i = 0; i < jsonArray.length(); i++) {
						Object obj = Class.forName(className).newInstance();
						convertJsonToObj(obj, jsonArray.getJSONObject(i));
						list.add(obj);
					}
				} else {
					List list = new ArrayList();
					f.set(convert, list);
					String genericTyp = f.getGenericType().toString();
					Object obj = Class.forName(
							genericTyp.substring(genericTyp.indexOf("<") + 1,
									genericTyp.indexOf(">"))).newInstance();
					convertJsonToObj(obj, (JSONObject) jsonObject);
					list.add(obj);
				}
			} else {
				if (json.get(jsonFied) == null) {
					continue;
				}
				f.set(convert, json.get(jsonFied));
			}
		}
	}
	
	private static final String TAG = "JSONUtil";  
    
    /** 
     * 获取json内容 
     * @param  url 
     * @return JSONArray 
     * @throws JSONException  
     * @throws ConnectionException  
     */  
    public static JSONObject getJSON(String url) throws JSONException, Exception {  
          
        return new JSONObject(getRequest(url));  
    }  
      
    /** 
     * 向api发送get请求，返回从后台取得的信息。 
     *  
     * @param url 
     * @return String 
     */  
    protected static String getRequest(String url) throws Exception {  
        return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));  
    }  
      
    /** 
     * 向api发送get请求，返回从后台取得的信息。 
     *  
     * @param url 
     * @param client 
     * @return String 
     */  
    protected static String getRequest(String url, DefaultHttpClient client) throws Exception {  
        String result = null;  
        int statusCode = 0;  
        HttpGet getMethod = new HttpGet(url);  
        Log.d(TAG, "do the getRequest,url="+url+"");  
        try {  
            //getMethod.setHeader("User-Agent", USER_AGENT);  
  
            HttpResponse httpResponse = client.execute(getMethod);  
            //statusCode == 200 正常  
            statusCode = httpResponse.getStatusLine().getStatusCode();  
            Log.d(TAG, "statuscode = "+statusCode);  
            //处理返回的httpResponse信息  
            result = retrieveInputStream(httpResponse.getEntity());  
        } catch (Exception e) {  
            Log.e(TAG, e.getMessage());  
            throw new Exception(e);  
        } finally {  
            getMethod.abort();  
        }  
        return result;  
    }  
      
    /** 
     * 处理httpResponse信息,返回String 
     *  
     * @param httpEntity 
     * @return String 
     */  
    protected static String retrieveInputStream(HttpEntity httpEntity) {  
                  
        int length = (int) httpEntity.getContentLength();         
        //the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.  
        //length==-1，下面这句报错，println needs a message  
        if (length < 0) length = 10000;  
        StringBuffer stringBuffer = new StringBuffer(length);  
        try {  
            InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);  
            char buffer[] = new char[length];  
            int count;  
            while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {  
                stringBuffer.append(buffer, 0, count);  
            }  
        } catch (UnsupportedEncodingException e) {  
            Log.e(TAG, e.getMessage());  
        } catch (IllegalStateException e) {  
            Log.e(TAG, e.getMessage());  
        } catch (IOException e) {  
            Log.e(TAG, e.getMessage());  
        }  
        return stringBuffer.toString();  
    }  
}
